﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SportsPlatform.HttpRequest
{
    public class WeiXinApi
    {
        #region OpenId获取

        /// <summary>
        /// 根据code获取openid
        /// </summary>
        /// <param name="appid">小程序ip</param>
        /// <param name="secret">小程序secret</param>
        /// <param name="code"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public static AuthResult Jscode2Session(string appid, string secret, string code, string type= "authorization_code")
        {
            AuthResult result=new AuthResult();
            try {
                string url = string.Format(@"https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type={3}", appid, secret, code, type);
                string ret = "";
                if (HttpRequest.HttpGet(url, out ret) == 0)
                {
                    string openid = JsonStrToDictionaryValue(ret, "openid");
                    if (!string.IsNullOrEmpty(openid))
                    {
                        result.Success = true;
                        result.OpenId = openid;
                    }
                    else
                    {
                        string error = JsonStrToDictionaryValue(ret, "errmsg");
                        result.Success = false;
                        result.ErrorMessage = string.IsNullOrEmpty(error) ? "返回解析报错！" : error;
                    }
                }
                else {
                    result.Success = false;
                    result.ErrorMessage = ret;
                }
            } catch (Exception ex) {
                result.Success = false;
                result.ErrorMessage = ex.Message.ToString();
            }
            return result;
        }
        #endregion

        #region 私有方法
        /// <summary>
        /// 从Json字串获取某个key的值
        /// </summary>
        /// <param name="jsonstr"></param>
        /// <returns></returns>
        public static string JsonStrToDictionaryValue(string jsonstr,string key)
        {
            string value = "";
            try {
                if (string.IsNullOrEmpty(jsonstr))
                {
                    return value;
                }
                Dictionary<string, string> jsonDict = JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonstr);
                value = jsonDict[key].ToString();
            }
            catch { }
            return value;
        }
        #endregion
    }
}
